import BaseModal, { type ModalInstance } from '@/components/BaseModal';
import { Picker } from '@react-native-picker/picker';
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { Platform, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import tw from 'twrnc';

interface ColumnItem {
  label: string;
  value: number | string;
}

interface IProps {
  columns: ColumnItem[],
  onChange?: Function,
  errorMessage?: string,
  errorStyle?: object
}

const BasePicker = React.memo(forwardRef((props: IProps, ref) => {
  const { errorMessage, errorStyle, columns = [], onChange } = props
  const modalRef = useRef<ModalInstance | null>(null)
  const [tempValue, setTempValue] = useState(null)

  useEffect(() => {
    if (!tempValue) return
    typeof onChange === 'function' && onChange(tempValue)
  }, [tempValue])

  const isIOS = useMemo(() => {
    return Platform.OS === 'ios'
  }, [])

  const labelIos = useMemo(() => {
    return columns.find(item => item.value === tempValue)?.label || null
  }, [tempValue, columns])

  const toggle = () => {
    if (!modalRef.current) return;
    modalRef.current.toggle()
  }

  const handleConfirm = () => {
    if (!tempValue) return
    typeof onChange === 'function' && onChange(tempValue)
    toggle()
  }

  useImperativeHandle(ref, () => {
    return {
      toggle,
    };
  });

  const renderPicker = () => {
    return <Picker
      selectedValue={tempValue}
      onValueChange={val => setTempValue(val)}
      style={{ backgroundColor: '#fff' }}
    >
      {columns.map(item => (
        <Picker.Item key={item.value} label={item.label} value={item.value} />
      ))}
    </Picker>
  }

  return <SafeAreaView>
    <View style={tw.style('px-[10px]')}>
    {
      isIOS ?
        // 1 个 Tailwind spacing 单位 = 4 dp， 例如：1px * 4 = 8dp
        <>
          <TouchableOpacity onPress={toggle}>
            <View><Text style={tw.style('leading-10')}>{labelIos || '请选择'}</Text></View>
          </TouchableOpacity>
          <BaseModal position='bottom' ref={modalRef}>
            <View style={tw.style('flex', 'flex-row', 'justify-between')}>
              <TouchableOpacity onPress={toggle}>
                <Text style={tw.style('text-lg')}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={handleConfirm}>
                <Text style={tw.style('text-lg')}>确定</Text>
              </TouchableOpacity>
            </View>
            {renderPicker()}
          </BaseModal>
        </>
        :
        renderPicker()
    }
    {/* 错误文本与样式 */}
    { errorMessage && <Text style={tw.style('text-xs', 'm-[5px]', errorStyle)}>{errorMessage}</Text> }
    </View>
  </SafeAreaView>;
}))

export type { ModalInstance };

export default BasePicker;